<?php
/**
 * Message List Main Interface
 * 
 * This interface retreive all messages according to a passed criteria
 * 
 * 
 */
use Fox\Generator;
use Fox\Behaviors;
use Doctrine\DBAL\Connection;
use Hive\Mission;
use Hive\Ressource;
use Fox\Dao\SqlFragment;
use Orx\Mailer\MailBox\Message;
$xview = Xview::instance();

$area = $xview->val('area','inbox');
$contactid = $xview->val('rid',null);
$reference = $xview->val('reference',null);
$splitted = $xview->val('splitted',false);
$status = $xview->val('status',null);
$notajax = $xview->val('notajax',false);
$coche = $xview->val('coche',true);
$limit = $xview->val('limit',null);
$mode = $xview->val('mode',false);
$summary = $xview->val('summary',false);
$content = null;
$limit = User::current()->getPrefs('mail-number');
$limit = empty($limit) ? 100 : $limit;
if($mode == 'widget') {
	$limit = 30; 
}
// Load all messages
$query = Fox\Dao::infos(Message::className())->handle()->createQueryBuilder()
			->select('m.messageid','m.idusr','m.boxid','m.status','m.parentid','m.received_date','m.email','m.name',
					'm.reference','m.reference_class_id','m.subject','m.content_html',
					'a.filename',
					'l.reference as directory_id','l.reference_class_id  as directory_type')
			->from('messages','m')
			->leftJoin('m','message_attachements','a','m.messageid = a.messageid')
			->leftJoin('m','message_labels','l','m.messageid = l.messageid')
			->setMaxResults($limit)
			->orderBy('m.received_date','DESC')
			;

if(!empty($contactid)){
	$area = 'contact';
}	
elseif(!empty($missionid)){
	$area = 'mission';

}

$showDeleted = false;
// Handle Status
if(!empty($status)) {
	if(is_numeric($status)) {
		$fragments[] = new SqlFragment('status = ?',array($status));
		if($status == Message::STATUS_DELETED) {
			$showDeleted = true;
		}
	} else {
		switch ($status) {
			case 'all' :
				$fragments[] = new SqlFragment('status NOT IN (?)',array(array(
					Message::STATUS_DELETED,Message::STATUS_SENT,Message::STATUS_DRAFT
				)),array(Connection::PARAM_INT_ARRAY));
				$showDeleted = false;
			break;
			default:
				$fragments[] = new SqlFragment('status IN (?)',array(array(
					Message::STATUS_UNREAD,Message::STATUS_READ
				)),array(Connection::PARAM_INT_ARRAY));
				$showDeleted = false;
			break;
		}
	}
} else {
	
}
if(!$showDeleted) {
	$fragments[] = new SqlFragment('loekz = ?',array(0));
}

// Area Handler
switch ($area) {
	case 'contact' :
		$contactid = !empty($contactid) ? $contactid : $xview->val('reference');
		$fragments[] = new SqlFragment('( (m.reference = ? AND m.reference_class_id = ?) OR 
										(r.reference = ? AND r.reference_class_id = ?) )',
									array($contactid,Ressource::MESSAGE_REFERENCE,
											$contactid,Ressource::MESSAGE_REFERENCE));
		$query->leftJoin('m','message_receivers','r','m.messageid = r.messageid');
		break;
	case 'mission' :
		$fragments[] = new SqlFragment('(m.reference = ? AND m.reference_class_id = ?) OR 
										(l.reference = ? AND l.reference_class_id = ?)',
									array($reference,Mission::MESSAGE_REFERENCE,
											$reference,Mission::MESSAGE_REFERENCE));
		break;	
	default :// inbox default area
		// User Specific Fragments
		$fragments[] = new SqlFragment('idusr = ?',array(User::current()->getId()));
		break;
}
if($limit > 0) {
	$query->setMaxResults($limit);
}
$fragment = SqlFragment::combine($fragments);
$messages = $fragment->pushIn($query)->execute()->fetchAll(PDO::FETCH_ASSOC);
// Regroup Conversation by parent
$finalMessages = $readMessages = $otherMessages = array();

foreach($messages as $message) {
	$data = $message;
	$labels = null;
	if(!empty($message['directory_id'])) {
		if($message['directory_type'] == Mission::MESSAGE_REFERENCE) {
			if($area == 'mission' && $reference == $message['directory_id']) {
				// Do not display the current mission label in a mission directory
			} else {
				$labels[] = array('label' => Mission::reference($message['directory_id']),
							  'id' => $message['directory_id'],
							'inlineid' => $message['messageid'].':'.$message['directory_id'].':'.Mission::MESSAGE_REFERENCE);
			}
		}
		
	}
	if(isset($finalMessages[$message['messageid']])) {
		if(isset($finalMessages[$message['messageid']]['labels'])) {
			$finalMessages[$message['messageid']]['labels'] = array_merge($finalMessages[$message['messageid']]['labels'],$labels);
		}
		
		if(!empty($data['filename'])) {
			$finalMessages[$message['messageid']]['attachements'] .= ','.$data['filename'];
		}
		
	} else {
		$data['labels'] = $labels;
		$data['attachements'] = $data['filename'];
		$finalMessages[$message['messageid']] = $data;
	}
	
	if($message['status'] == Message::STATUS_UNREAD) {
		$readMessages[$message['messageid']] = $finalMessages[$message['messageid']];
	} else {
		$otherMessages[$message['messageid']] = $finalMessages[$message['messageid']];
	}
	
}
// Output Search Result
$grid = $xview->component('messages','grid');
if($coche && $mode != 'widget') {
	$grid->setCoche();
	$grid->fieldcat()->field('coche')->setClass('mail-checker');
}

if(($splitted || $status == 'inbox') && !$mode) {
	$grid->initialize($otherMessages);
	$gridUnread = $xview->component('messages','grid');
	$gridUnread->id('unread_messages');
	if($coche) {
		$gridUnread->setCoche();
		$gridUnread->fieldcat()->field('coche')->setClass('mail-checker');
	}
	$gridUnread->initialize($readMessages);
	$html[] = '<div class="unread-messages"><h2>'.Msg(Orx\Mailer\Messages::BUNDLE,Orx\Mailer\Messages::UNREAD).'</h2>';
	$html[] = $gridUnread->display();
	$html[] = '</div>';
	$html[] = '<div class="other-messages"><h2>'.Msg(Orx\Mailer\Messages::BUNDLE,Orx\Mailer\Messages::OTHER_MESSAGES).'</h2>';
	$html[] = $grid->display();
	$html[] = '</div>';
	$content = implode('',$html);
	 
} else {
	if(count($messages) == 0) {
		Fox\Message::Warning(Msg(Orx\Mailer\Messages::BUNDLE,Orx\Mailer\Messages::SORRY_NO_MESSAGE_FOUND));
	} else {
		$grid->initialize($finalMessages);
		$content = $grid->display();
	}
}
$behavior = new Behaviors();
$behavior->add(Behaviors::source(Generator::url('messages','list',null,
	array('reference' => $reference,'status' => $status,
		  'area'=> $area,'summary' => $summary,
		  'xvtrs' => 'none','mode' => $mode)
)));

$content = '<div class="'.$behavior->serialize(array(),'list').'">'.$content.'</div>';
\Fox\Ressources::instance()->register(new \Fox\Ressources\Script(_ASSETS_.'js/mailbox-list.js'));
$content .= \Fox\Ressources::instance()->dump();

if($notajax) {
	return $content;
} else {
	echo $xview->messages(true);
	echo $content;
}